package cdp.tarasenko.task1;

import java.util.HashMap;

/**
 * @Author( name = Oleksandr_Tarasenko,
 * date = 26.07.13 )
 *
 * Implementation of LRU cache.
 */
public class LRUCache<T, U> {
    private long count = 0;
    private HashMap<T, U> cache = new HashMap<T, U>();
    protected PriorityQueue<T> priorityQueue = new PriorityQueue<T>();

    private int maxCacheSize;

    public LRUCache(int maxCacheSize) {
        this.maxCacheSize = maxCacheSize;
    }

    public int getSize() {
        return cache.size();
    }

    public void add(T key, U value) {
        if (cache.size() >= maxCacheSize) {
            T oldestItem = priorityQueue.pull();
            cache.remove(oldestItem);
        }
        cache.put(key, value);
        updatePriority(key);
        count++;
    }

    public U get(T key) {
        if (getSize() == 0) return null;
        priorityQueue.remove(key);
        updatePriority(key);
        return cache.get(key);
    }

    protected void updatePriority(T key) {
        priorityQueue.add(key, count);
    }
}
